<template>
  <div>
    <ListHeader title="选择品牌" />
    <select-container-box>
      <SelectSearch
        ref="cslRef"
        slot="box-search"
        :searchName.sync="brandName"
        @searchData="getBrandListBySearch"
      />
      <select-show-list slot="box-list">
        <el-checkbox-group v-model="checkCodeList" v-loading="searchLoading" @change="handleSelectBrand">
          <div v-for="brandInfo in brandList" :key="brandInfo.brandAndSeriesUuid">
            <el-checkbox :label="brandInfo.brandAndSeriesUuid">
              {{ brandInfo.brandAndSeriesName }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </select-show-list>
    </select-container-box>
  </div>
</template>
<script>
import ListHeader from './ListHeader';
import SelectContainerBox from './SelectContainerBox';
import SelectSearch from './SelectSearch';
import SelectShowList from './SelectShowList';
import { getBrandSeriesByBrandNameService } from '@/api/public';
import { eventBus } from '../eventBus';
export default {
  components: {
    ListHeader,
    SelectContainerBox,
    SelectSearch,
    SelectShowList
  },
  data () {
    return {
      checkCodeList: [],
      brandList: [],
      checkBrandMaps: new Map(),
      brandName: '',
      searchLoading: false
    }
  },
  created () {
    eventBus.$on('updateSelectBrands', codes => {
      this.checkCodeList = codes
    })
  },
  methods: {
    // 获取根据名称查询获取品牌查询集合
    getBrandListBySearch () {
      this.handleSearchBrandList()
    },
    // 查询品牌集合
    async handleSearchBrandList () {
      const data = { brandName: this.brandName }
      const loadingFn = state => { this.searchLoading = state }
      const res = await getBrandSeriesByBrandNameService(data, loadingFn)
      if (!res) return
      if (res.retData && res.retData.length == 0) {
        this.brandList = []
        return this.$message.warning('未查询到品牌信息')
      }
      this.brandList = res.retData ?? []
    },
    // 选择品牌
    handleSelectBrand (codeList) {
      const brandMaps = new Map(this.brandList.map(item => [item.brandAndSeriesUuid, item])) // 当前搜索结果的集合Map
      codeList.forEach(code => {
        if (brandMaps.has(code)) { // 当前勾选编码结果存在于搜索结果集中，便将该项添加至勾选Map结果集中
          this.checkBrandMaps.set(code, brandMaps.get(code))
        }
      })
      this.checkBrandMaps.forEach((value, key) => {
        if (!codeList.includes(key)) { // 当前勾选编码结果不包含勾选Map的code时，便从勾选Map移除该项
          this.checkBrandMaps.delete(key)
        }
      })
      eventBus.$emit('selectBrand', this.checkBrandMaps)
    },
    // 清空品牌搜索结果
    clearResults () {
      this.$refs.cslRef.clearSearchState()
      this.checkCodeList = []
      this.brandList = []
      this.checkBrandMaps = new Map()
      eventBus.$emit('selectBrand', this.checkBrandMaps)
    }
  }
}
</script>
